/**
 * Created by zhoux on 2016/2/16.
 */
var fs = require("fs");
var __extends = this.__extends || function (d, b) {
        function __() { this.constructor = d; }
        __.prototype = b.prototype;
        d.prototype = new __();
    };
var ArchiveLoader = (function () {
    function ArchiveLoader(archiveName) {
        this.fileName = archiveName;
        this.__fdFile = fs.openSync(archiveName, "r");
    }

    ArchiveLoader.prototype.__fileRead = function (offset, length) {
        var buf = new Buffer(length);
        fs.readSync(this.__fdFile, buf, 0, length, offset);
        return buf;
    };
    ArchiveLoader.prototype.getFileList = function () {
        return [];
    };
    ArchiveLoader.prototype.getFileByIndex = function (index) {
        return new Buffer(0);
    };
    ArchiveLoader.prototype.close = function () {
        fs.closeSync(this.__fdFile);
    };
    ArchiveLoader.__loaders = {};
    ArchiveLoader.registerLoader = function registerLoader(ext, loader) {
        ArchiveLoader.__loaders[ext] = loader;
    };
    ArchiveLoader.createFileLoader = function createFileLoader(ext, fileName) {
        return new ArchiveLoader.__loaders[ext](fileName);
    };
    return ArchiveLoader;
})();

var jszip = require("node-zip");
var ZipLoader = (function (_super) {
    __extends(ZipLoader, _super);
    function ZipLoader(zipName) {
        _super.call(this, zipName);
        this.zip = null;
        this.files = [];
        this.zip = jszip(this.__fdFile);
        this.files = this.zip.zipEntries.files.reduce(function (arr, file) {
            var imageExt = /\.(jpg|jpeg|png|gif)$/i;
            if (imageExt.test(file.fileName)) {
                arr.push({
                    name: file.fileName,
                    content: file
                });
            }
            return arr;
        }, []).sort(function (fileA, fileB) {
            return (fileA.name > fileB.name) ? 1 : (fileA.name < fileB.name) ? -1 : 0;
        });
    }

    ZipLoader.prototype.getFileList = function () {
        return this.files;
    };
    ZipLoader.prototype.getFileByIndex = function (index) {
        return new Buffer(this.zip.zipEntries.readLocalFile(this.files[index].content), "binary");
    };
    ZipLoader.prototype.close = function () {
    };
    return ZipLoader;
})(ArchiveLoader);
ArchiveLoader.registerLoader("zip", ZipLoader);
var archiveLoader;
var loadArchive = function (query) {
    if (archiveLoader && archiveLoader.fileName !== query.file) {
        archiveLoader.close();
        archiveLoader = undefined;
    }
    if (!archiveLoader) {
        archiveLoader = ArchiveLoader.createFileLoader(query.type.toLocaleLowerCase(), query.file);
    }
    return archiveLoader;
};

exports.archiveLoader = archiveLoader;
exports.loadArchive = loadArchive;



